/*
 * Copyright (C) 2011 Nicola Bonzanni
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package nl.vu.few.ibivu.jlemon;

import java.util.ListIterator;
import java.util.NoSuchElementException;

import nl.vu.few.ibivu.jlemon.concepts.Arc;
import nl.vu.few.ibivu.jlemon.concepts.Path;

public class PathIterator<A extends Arc & Comparable<A>> extends AbstractIterator<A> implements ListIterator<A> {

	protected Path<A> path;
	protected A previous;
	// i points to the current element
	protected int i;
	
	public PathIterator(Path<A> path, boolean reverse) {
		super();
		this.path = path;
		if (reverse) {
			i = path.length();
			current = null;
			previous = path.back();
		}
		else {
			i = -1;
			current = null;
			next = path.front();			
		}
	}
	
	public PathIterator(Path<A> path, int n) {
		super(path.nth(n), null);
		this.path = path;
		this.i = n;
		this.next = computeNext();
		this.previous = computePrevious();
	}

	// The following two function should be overridden and
	// optimized by the different type of path implementations
	@Override
	protected A computeNext() {
		return path.nth(i + 1);
	}
	
	protected A computePrevious() {
		return path.nth(i - 1);
	}

	@Override
	public void add(A e) {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean hasPrevious() {
		return previous != null;
	}
	
	@Override
	public A next() {
		if (!hasNext()) {
			throw new NoSuchElementException();
		}
		previous = current;
		current = next;
		next = computeNext();
		i++;
		return current;
	}

	@Override
	public int nextIndex() {
		return i + 1;
	}

	@Override
	public A previous() {
		if (!hasPrevious()) {
			throw new NoSuchElementException();
		}
		next = current;
		current = previous;
		previous = computePrevious();
		i--;
		return current;
	}

	@Override
	public int previousIndex() {
		return i - 1;
	}

	@Override
	public void set(A e) {
		throw new UnsupportedOperationException();
	}

}
